<template>
  <div class="user-group-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>用户分组管理</span>
          <el-button type="primary" @click="showAddGroupDialog">新增分组</el-button>
        </div>
      </template>
      
      <!-- 搜索 -->
      <div class="search-filter">
        <el-input v-model="searchQuery" placeholder="搜索分组名称" prefix-icon="Search" style="width: 300px; margin-right: 15px;"></el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      
      <!-- 分组表格 -->
      <el-table :data="groupsData" style="width: 100%">
        <el-table-column prop="id" label="分组ID" width="80"></el-table-column>
        <el-table-column prop="name" label="分组名称" width="180"></el-table-column>
        <el-table-column prop="description" label="分组描述"></el-table-column>
        <el-table-column prop="userCount" label="用户数量" width="120"></el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 'active' ? 'success' : 'danger'">
              {{ scope.row.status === 'active' ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button type="primary" size="small" @click="showEditGroupDialog(scope.row)">编辑</el-button>
            <el-button type="info" size="small" @click="viewGroupUsers(scope.row)">查看用户</el-button>
            <el-button :type="scope.row.status === 'active' ? 'danger' : 'success'" size="small" @click="handleToggleStatus(scope.row)">
              {{ scope.row.status === 'active' ? '禁用' : '启用' }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>
    
    <!-- 新增/编辑分组对话框 -->
    <el-dialog v-model="groupDialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="groupForm" :rules="groupRules" ref="groupFormRef" label-width="120px">
        <el-form-item label="分组名称" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入分组名称"></el-input>
        </el-form-item>
        <el-form-item label="分组描述" prop="description">
          <el-input v-model="groupForm.description" type="textarea" :rows="3" placeholder="请输入分组描述"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="groupForm.status" active-value="active" inactive-value="inactive"></el-switch>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="groupDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSaveGroup">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 分组用户列表对话框 -->
    <el-dialog v-model="groupUsersDialogVisible" title="分组用户列表" width="800px">
      <el-table :data="groupUsersData" style="width: 100%">
        <el-table-column prop="id" label="用户ID" width="80"></el-table-column>
        <el-table-column prop="username" label="用户名" width="120"></el-table-column>
        <el-table-column prop="phone" label="手机号" width="150"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="200"></el-table-column>
        <el-table-column prop="joinedAt" label="加入时间" width="180"></el-table-column>
      </el-table>
      <template #footer>
        <el-button @click="groupUsersDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'

// 搜索条件
const searchQuery = ref('')

// 表格数据
const groupsData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(20)

// 对话框状态
const groupDialogVisible = ref(false)
const groupUsersDialogVisible = ref(false)
const editingGroupId = ref(null)
const groupFormRef = ref()

// 分组表单
const groupForm = reactive({
  name: '',
  description: '',
  status: 'active'
})

// 分组用户数据
const groupUsersData = ref([])

// 表单验证规则
const groupRules = {
  name: [
    { required: true, message: '请输入分组名称', trigger: 'blur' },
    { min: 2, max: 50, message: '分组名称长度在 2 到 50 个字符', trigger: 'blur' }
  ]
}

// 对话框标题
const dialogTitle = computed(() => {
  return editingGroupId.value ? '编辑用户分组' : '新增用户分组'
})

// 获取分组列表
const fetchGroups = () => {
  // 实际项目中应该从后端获取数据
  // 这里使用模拟数据
  const mockData = [
    { id: 1, name: '提肛运动', description: '提肛运动用户组', userCount: 580, status: 'active', createdAt: '2023-07-01 10:00:00' },
    { id: 2, name: '鼻炎护理', description: '鼻炎护理用户组', userCount: 420, status: 'active', createdAt: '2023-07-02 11:00:00' },
    { id: 3, name: '综合健康', description: '综合健康管理用户组', userCount: 280, status: 'active', createdAt: '2023-07-03 12:00:00' }
  ]
  
  // 应用搜索
  let filteredData = [...mockData]
  if (searchQuery.value) {
    filteredData = filteredData.filter(group => 
      group.name.includes(searchQuery.value)
    )
  }
  
  total.value = filteredData.length
  
  // 分页
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  groupsData.value = filteredData.slice(start, end)
}

// 显示新增分组对话框
const showAddGroupDialog = () => {
  editingGroupId.value = null
  // 重置表单
  if (groupFormRef.value) {
    groupFormRef.value.resetFields()
  }
  // 重置表单数据
  groupForm.name = ''
  groupForm.description = ''
  groupForm.status = 'active'
  groupDialogVisible.value = true
}

// 显示编辑分组对话框
const showEditGroupDialog = (group) => {
  editingGroupId.value = group.id
  groupForm.id = group.id
  groupForm.name = group.name
  groupForm.description = group.description
  groupForm.status = group.status
  groupDialogVisible.value = true
}

// 保存分组
const handleSaveGroup = () => {
  groupFormRef.value.validate((valid) => {
    if (valid) {
      // 实际项目中应该调用API保存数据
      ElMessage.success(editingGroupId.value ? '分组编辑成功' : '分组新增成功')
      groupDialogVisible.value = false
      fetchGroups()
    }
  })
}

// 切换分组状态
const handleToggleStatus = (group) => {
  const newStatus = group.status === 'active' ? 'inactive' : 'active'
  // 实际项目中应该调用API更新状态
  ElMessage.success(`分组已${newStatus === 'active' ? '启用' : '禁用'}`)
  fetchGroups()
}

// 查看分组用户
const viewGroupUsers = (group) => {
  // 实际项目中应该从后端获取数据
  // 这里使用模拟数据
  groupUsersData.value = [
    { id: 1, username: '张三', phone: '13800138001', email: 'zhangsan@example.com', joinedAt: '2023-07-01 10:00:00' },
    { id: 2, username: '李四', phone: '13800138002', email: 'lisi@example.com', joinedAt: '2023-07-02 11:00:00' },
    { id: 3, username: '王五', phone: '13800138003', email: 'wangwu@example.com', joinedAt: '2023-07-03 12:00:00' }
  ]
  groupUsersDialogVisible.value = true
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchGroups()
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''
  currentPage.value = 1
  fetchGroups()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchGroups()
}

const handleCurrentChange = (current) => {
  currentPage.value = current
  fetchGroups()
}

// 初始化数据
fetchGroups()
</script>

<style scoped>
.user-group-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-filter {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>